//定义js命名空间
Ext.namespace('FsCarInfo.FsGatelogList');
//TODO : 完善数据结构
//DateTime -- date , decimal -- float
// { name: 'Department.Name', mapping: 'Department.Name' },
// { name: 'Department'},
//FsGatelogList FieldArray
FsCarInfo.FsGatelogList.BaseFieldsArray = new Array(
	{ name: 'Id', type: 'string' },
	{ name: 'LogId', type: 'string' },
	{ name: 'GateId', type: 'string' },
	{ name: 'Createuser', type: 'string' },
	{ name: 'Description', type: 'string' },
	{ name: 'ApprUserId', type: 'string' },
	{ name: 'ApprTime', type: 'string' },
	{ name: 'ApprState', type: 'int' },
	{ name: 'Createtime', type: 'DateTime' },
	{ name: 'ImgPath', type: 'string' },
	{ name: 'Version', type: 'int' },
	{ name: 'Isdelete', type: 'bool' }
);

//FsGatelogList JsonReader
FsCarInfo.FsGatelogList.JsonReader = Ext.extend(Infrastructure.BaseJsonReader, {
    constructor: function (cfg) {
        cfg = cfg || {};
        FsCarInfo.FsGatelogList.JsonReader.superclass.constructor.call(this, Ext.apply({
            fields: FsCarInfo.FsGatelogList.BaseFieldsArray
        }, cfg));
    }
});

//FsGatelogList JsonStore
FsCarInfo.FsGatelogList.JsonStore = Ext.extend(Infrastructure.BaseJsonStore, {
    constructor: function (cfg) {
        cfg = cfg || {};
        FsCarInfo.FsGatelogList.JsonStore.superclass.constructor.call(this, Ext.apply({
            url: '/FsGatelogList/GetPlistAll',
			params: {
                start: 0,
                limit: ALL_PAGESIZE_SETTING
            },
            remoteSort: true,
            fields : FsCarInfo.FsGatelogList.BaseFieldsArray,
            listeners: {
                'remove': function (thiz, record, index) {
                    Ext.Ajax.request({
                        url: '/FsGatelogList/Delete?Id=' + record.data.Id,
                        success: function (response, opts) {
                            var result = Ext.util.JSON.decode(response.responseText);
                            if (result.success == false) {
                                JsHelper.ShowError(result.msg);
                                this.insert(0, record);
                            }
                        }
                    });
                }
            }
        }, cfg));
    }
});

//FsGatelogList GridPanel
FsCarInfo.FsGatelogList.GridPanel = Ext.extend(Ext.grid.GridPanel, {
	// User property
	//基本处理Url
    baseUrl: '/FsGatelogList/',
	//提交保存Url
	formSubmitUrl: '/FsGatelogList/SaveOrUpdate', 
	//提交保存提示信息
	formSubmitMsg: '确定要保存吗?',	
	//工具栏标签
    tbarMask: '0',
    //表格列默认显示
    columnMask: '012345600001230000090123000000',
    //状态
    itemState: '',
	
	// Property
    stripeRows: true,
    frame: true,
    border: true,
    layout: 'fit',
    loadMask: true,
    enableColumnMove: false,
    viewConfig: {
        autoFill: true
    },
    store: new FsCarInfo.FsGatelogList.JsonStore(),
    stateful: true,
    stateId: 'FsCarInfo.FsGatelogList.GridPanel',
	
	//constructor
    initComponent: function () {
		//prepare
		
		var itemGrid = this;
		var tbarMask = this.tbarMask;
        var colMask = this.columnMask;
        var cmdAddEntity = this.onAddEntity;
        var cmdDeleteEntity = this.onDeleteEntity;
        var cmdLoadEntity = this.onLoadEntity;
        var cmdQueryList = this.onQueryList;
        //提交审批
        var cmdTbarCmd = function () {
            this.tbarSubmit(this.baseUrl + 'MethodName', '确定要提交吗?', '您的信息提交到系统..');
        };
		//set store params
		this.store.setBaseParam('state', this.itemState);
		
		// The filter.
        var gridFilter = new Ext.ux.grid.GridFilters({
            encode: true,
			filters: [
				{ dataIndex: 'Id', type: 'string' },
				{ dataIndex: 'LogId', type: 'string' },
				{ dataIndex: 'GateId', type: 'string' },
				{ dataIndex: 'Createuser', type: 'string' },
				{ dataIndex: 'Description', type: 'string' },
				{ dataIndex: 'ApprUserId', type: 'string' },
				{ dataIndex: 'ApprTime', type: 'string' },
				{ dataIndex: 'ApprState', type: 'string' },
				{ dataIndex: 'Createtime', type: 'string' },
				{ dataIndex: 'ImgPath', type: 'string' },
				{ dataIndex: 'Version', type: 'string' },
				{ dataIndex: 'Isdelete', type: 'string' }
            ]
        });
		
		// selModel
        var selModel = new Ext.grid.CheckboxSelectionModel({
            //header: '',
            //singleSelect: true,
            listeners: {
                'selectionchange': function (sm) {
                    // 控制工具栏按钮是否可用
                    itemGrid.delBtn.setDisabled(sm.getCount() < 1);
				}
			}
		});
		
		// columnModel 对于不常需要显示的 hidden: true 
		var gridColumn = new Ext.grid.ColumnModel({
			columns: [
				new Ext.grid.RowNumberer(),
				selModel, 
				{ header: "出入记录ID", dataIndex: 'LogId', hidden: this.columnMask.charAt(1) == '0' }, 
				{ header: "闸机", dataIndex: 'GateId', hidden: this.columnMask.charAt(1) == '0' }, 
				{ header: "授权人", dataIndex: 'ApprUserId', hidden: this.columnMask.charAt(1) == '0' }, 
				{ header: "授权时间", dataIndex: 'ApprTime', hidden: this.columnMask.charAt(1) == '0' }, 
				{ header: "状态", dataIndex: 'ApprState', hidden: this.columnMask.charAt(1) == '0' }, 
				{ header: "截图路径", dataIndex: 'ImgPath', hidden: this.columnMask.charAt(1) == '0' }
			]
		});
		
		// PageBar
        var pagebBar = new Infrastructure.BasePagingToolbar({
            store: this.store,
            plugins: this.plugins
        });
		
		// 常用工具栏
        var toolBar = [{
            xtype: 'tbaraddbtn',
            hidden: tbarMask.substring(0, 1) != '1',
            handler: cmdAddEntity,
            scope: itemGrid
        }, {
            hidden: tbarMask.substring(0, 1) != '1',
            xtype: 'tbseparator'
        }, {
            xtype: 'tbardelbtn',
            hidden: tbarMask.substring(0, 1) != '1',
            handler: cmdDeleteEntity,
            scope: itemGrid
        }, '-', {
            xtype: 'textfield',
            width: 150,
            id: 'q_query'
        }, {
            xtype: 'tbarqrybtn',
            handler: cmdQueryList,
            scope: itemGrid
        }, '-'];
		
		Ext.apply(this, {
            plugins: [gridFilter],
            sm: selModel,
            cm: gridColumn,
            tbar: toolBar,
            bbar: pagebBar,
            listeners: {
                'rowdblclick': cmdLoadEntity
            }
        });
		
        FsCarInfo.FsGatelogList.GridPanel.superclass.initComponent.call(this);
    },
	
	/****************** 
    * user function 
    ******************/

    // 添加
	onAddEntity: function () {
        var itemGrid = this;
        var itemEditForm = new FsCarInfo.FsGatelogList.EditForm({
            listeners: {
                'afterSave': function (ele, rt) {
                    if (rt) {
                        ele.form.reset();
                        var itemGridStore = itemGrid.store;
                        itemGridStore.reload();
                        JsHelper.ShowInfo('添加信息成功!');
                    }
                }
            }
        });
        var itemEditWin = new FsCarInfo.FsGatelogList.EditWin({
            items: [itemEditForm]
        });
        itemEditWin.show();
    },

    // 读取信息显示
    onLoadEntity: function () {
        var itemGrid = this;
        var selRecord = this.getSelectionModel().getSelected();
        if (selRecord == null) {
            JsHelper.ShowError('请选择记录编辑..');
            return -1;
        }
        var selId = selRecord.data.Id;
        var itemEditForm = new FsCarInfo.FsGatelogList.EditForm({
            Id: selId,
			dataRecord: selRecord,
			submitUrl : this.formSubmitUrl,
            submitMsg : this.formSubmitMsg,
            waitMsg: '数据加载中...',
            listeners: {
                'afterSave': function (ele, rt) {
                    if (rt) {
                        itemGrid.store.reload();
                        JsHelper.ShowInfo('信息更新成功!');
                    }
                }
            }
        });
        var itemEditWin = new FsCarInfo.FsGatelogList.EditWin({
            items: [itemEditForm]
        });
        itemEditWin.show();
        itemEditForm.form.loadRecord(selRecord);
    },

    // 删除
    onDeleteEntity: function () {
        var itemGrid = this;
        var itemGridStore = this.store;
        JsHelper.DelConfirm(function (btn) {
            if (btn == 'yes') {
                var s = itemGrid.getSelectionModel().getSelections();
                for (var i = 0, r; r = s[i]; i++) {
                    itemGridStore.remove(r);
                }
            }
        });
    },

    // 查询
    onQueryList: function () {
        var itemGrid = this;
        var q_query = Ext.getCmp('q_query').getValue();
        itemGrid.store.load({
            params: {
                start: 0,
                limit: ALL_PAGESIZE_SETTING,
                q_query: q_query
            }
        })
    },

    // 提交选定记录..
    tbarSubmit: function (submitUrl, confirmMsg, successMsg) {
        var itemGrid = this;
        var selRecord = this.getSelectionModel().getSelected();
        if (selRecord == null) {
            JsHelper.ShowError('未选择记录.');
            return -1;
        }
        var selId = selRecord.data.Id;
        JsHelper.Confirm(confirmMsg, function (btn) {
            if (btn == 'yes') {
                var ids = [];
                var s = itemGrid.getSelectionModel().getSelections();
                for (var i = 0, r; r = s[i]; i++) {
                    ids.push(r.data.Id);
                }
                //加载进度条
                Ext.MessageBox.show({
                    msg: '正在提交数据到中心服务器...',
                    progressText: '保存数据...',
                    width: 300,
                    wait: true,
                    waitConfig: { interval: 1000 }
                });
                Ext.Ajax.request({
                    url: submitUrl,
                    params: {
                        'Ids': ids.toString()
                    },
                    success: function (response, opts) {
                        Ext.MessageBox.hide();
                        var result = Ext.util.JSON.decode(response.responseText);
                        if (result.success == false) {
                            JsHelper.ShowError('操作失败:' + result.msg);
                        } else {
                            itemGrid.store.reload();
                            Ext.Msg.alert('提示,操作成功', '成功。' + successMsg);
                        }
                    },
                    failure: function (form, action) {
                        Ext.MessageBox.hide();
                        JsHelper.ShowError('系统异常:' + action.result.msg);
                    }
                });
            }
        });
    }
});

//FsGatelogList EditForm
FsCarInfo.FsGatelogList.EditForm = Ext.extend(Infrastructure.BaseForm, {
	Id : null,
	dataRecord: null,
	submitUrl: '/FsGatelogList/SaveOrUpdate',
	submitMsg: '确定要保存吗?',
		
    initComponent: function () {
		var itemEditForm = this;
        var cmdUpdate = this.onSave;
		
        //Form第一列
        // 定义表单列
		var firstColumn = [{
			fieldLabel: "出入记录ID",
			width: 150,
			maxLength: 36,
			xtype: 'textfield',
			name: 'LogId'
		}, {
			fieldLabel: "闸机",
			width: 150,
			maxLength: 36,
			xtype: 'textfield',
			name: 'GateId'
		}, {
			fieldLabel: "授权人",
			width: 150,
			maxLength: 36,
			xtype: 'textfield',
			name: 'ApprUserId'
		}, {
			fieldLabel: "授权时间",
			width: 150,
			maxLength: 50,
			xtype: 'textfield',
			name: 'ApprTime'
		}, {
			fieldLabel: "状态",
			width: 150,
			maxLength: 0,
			xtype: 'textfield',
			name: 'ApprState'
		}, {
			fieldLabel: "截图路径",
			width: 150,
			maxLength: 50,
			xtype: 'textfield',
			name: 'ImgPath'
		}, ];

        //Form第二列
        var secondColumn = [{
            fieldLabel: 'Column2',
			readOnly: true,
            width: 150
        }];

        //Form单列
        var singleColumn = [{
            xtype: 'textarea',
            fieldLabel: '描述',
            name: 'Description',
            height: 50,
            width: 430
        }];

        Ext.apply(this, {
            items: [{
                layout: 'column',
                // 注意 现在使用的是两列 要是三列或更多
                // 请改变下面的items
                // 并在上面定义每个列的组件集合
                items: [{
                    columnWidth: .5,
                    bodyStyle: 'padding:1px',
                    layout: 'form',
                    defaultType: 'textfield',
                    items: firstColumn
                }, {
                    columnWidth: .5,
                    bodyStyle: 'padding:1px',
                    layout: 'form',
                    defaultType: 'textfield',
                    items: secondColumn
                }]
            }, singleColumn],
			buttons: [{
                xtype: 'btnsubmit',
                handler: cmdUpdate,
                hidden: this.submitUrl == '',
                scope: itemEditForm
            }, {
                xtype: 'btncancle',
                handler: function () {
                    itemEditForm.ownerCt.destroy();
                }
            }],
            reader: new FsCarInfo.FsGatelogList.JsonReader()
        });
		
		FsCarInfo.FsGatelogList.EditForm.superclass.initComponent.call(this);
		
		//定义保存后执行的事件
        this.addEvents('afterSave');
    },

    /****************** 
    * user function 
    ******************/

    //更新保存信息
    onSave: function () {
        var itemForm = this;
        var id = this.Id;
        var saveUrl = this.submitUrl;
        if (itemForm.getForm().isValid()) {
			JsHelper.Confirm(this.submitMsg, function (btn) {
                if (btn != 'no') {
					itemForm.getForm().submit({
						waitMsg: '正在提交....',
						url: saveUrl,
						params: {
							'Id': (id == null) ? '' : id
						},
						success: function (form, action) {
							//返回结果后触发保存事件
							itemForm.fireEvent('afterSave', itemForm, true);
						},
						failure: function (form, action) {
							JsHelper.ShowError(action.result.msg);
						}
					});
				}
			});
        }
    }
});

//FsGatelogList DetailWin
FsCarInfo.FsGatelogList.EditWin = Ext.extend(Ext.Window, {
	title: 'FsGatelogList Infomation',
    iconCls: 'application_form',
    width: 600,
    resizable: false,
    constrain: true,
    autoHeight: true,
    modal: true,
    closeAction: 'close',
    plain: true,
	buttonAlign: 'center',
	
	//constructor
    initComponent: function () {
        FsCarInfo.FsGatelogList.EditWin.superclass.initComponent.call(this);
	}
});
